/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.nifi.processors.huawei.obs;

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.annotation.behavior.InputRequirement.Requirement;
import org.apache.nifi.annotation.behavior.SupportsBatching;
import org.apache.nifi.annotation.behavior.WritesAttribute;
import org.apache.nifi.annotation.behavior.WritesAttributes;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processors.huawei.abstractprocessor.AbstractOBSProcessor;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.apache.nifi.processors.huawei.common.PropertyDescriptors.*;


@SupportsBatching
@WritesAttributes({
        @WritesAttribute(attribute = Constants.OBS_EXCEPTION, description = "The class name of the exception thrown during processor execution"),
        @WritesAttribute(attribute = Constants.OBS_ADDITIONAL_DETAILS, description = "The OBS supplied detail from the failed operation"),
        @WritesAttribute(attribute = Constants.OBS_STATUS_CODE, description = "The HTTP error code (if available) from the failed operation"),
        @WritesAttribute(attribute = Constants.OBS_ERROR_CODE, description = "The OBS moniker of the failed operation"),
        @WritesAttribute(attribute = Constants.OBS_ERROR_Message, description = "The OBS exception message from the failed operation")})
@Tags({"HuaweiCloud", "obs", "Archive", "Delete"})
@InputRequirement(Requirement.INPUT_REQUIRED)
@CapabilityDescription("Deletes FlowFiles on an HuaweiCloud OBS Bucket. " +
        "If attempting to delete a file that does not exist, FlowFile is routed to success.")
public class DeleteOBSObject extends AbstractOBSProcessor {
    public static final List<PropertyDescriptor> properties = Collections.unmodifiableList(
            Arrays.asList(OBS_REGION, ENDPOINT_OVERRIDE_URL, BUCKET, ACCESS_KEY, SECRET_KEY, HUAWEI_CREDENTIALS_PROVIDER_SERVICE, KEY,  TIMEOUT,
//                    SSL_CONTEXT_SERVICE,
                    PROXY_CONFIGURATION_SERVICE));

    @Override
    public List<PropertyDescriptor> getSupportedPropertyDescriptors() {
        return properties;
    }

    @Override
    public void onTrigger(final ProcessContext context, final ProcessSession session) {
        FlowFile flowFile = session.get();
        if (flowFile == null) {
            return;
        }

        final long startNanos = System.nanoTime();

        final String bucket = context.getProperty(BUCKET).evaluateAttributeExpressions(flowFile).getValue();
        final String key = context.getProperty(KEY).evaluateAttributeExpressions(flowFile).getValue();
        final String region = context.getProperty(OBS_REGION).getValue();
        final String endpoint = context.getProperty(ENDPOINT_OVERRIDE_URL).getValue();

        final ObsClient obsClient = getClient();
        // Deletes a key
        try {
             obsClient.deleteObject(bucket, key);
        } catch (final ObsException e) {
            flowFile = extractExceptionDetails(e, session, flowFile);
            getLogger().error("Failed to delete OBS Object for {}; routing to failure", flowFile, e);
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
            return;
        }

        session.transfer(flowFile, REL_SUCCESS);
        final long transferMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
        getLogger().info("Successfully delete OBS Object for {} in {} millis; routing to success", flowFile, transferMillis);
        session.getProvenanceReporter().invokeRemoteProcess(flowFile, OBSUtils.getUrl(region,endpoint, bucket, key), "Object deleted");
    }
}
